﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using LogViewApp.ViewModel;
using System.Xml.Linq;
using LogViewApp.Models;
using System.Diagnostics;
using LogViewApp.ServiceReference1;

namespace LogViewApp.Views
{
    public partial class LogView : Page
    {
        
        public LogView()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string xmlFileName = NavigationContext.QueryString["Log"];
            string guidString = NavigationContext.QueryString["Guid"];


            //DataContext="{Binding Source={StaticResource Locator}, Path=logViewModel}
            var locator = Application.Current.Resources["Locator"] as ViewModelLocator;

            LogViewModel logViewModel = locator.GetLogViewModel(guidString);
            this.DataContext = logViewModel;

            logViewModel.ParseUri(xmlFileName, guidString);
            logViewModel.UpdateDataAsync();
        }

        private void logItemsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            xmlTree.Items.Clear();
            foreach (var item in e.AddedItems)
            {
                LogItem logitem = item as LogItem;
                try
                {
                    XElement xTemp = XElement.Parse(logitem.WholeLog);
                    if (xTemp != null)
                    {
                        
                        xmlTree.Items.Add(LogViewModel.CreateTreeView(xTemp));
                    }
                }
                catch
                {

                }
            }
        }

        private void TextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                TextBox senderTextBox = sender as TextBox;
                if (senderTextBox != null)
                {
                    senderTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();

                    var logViewModel = this.DataContext as LogViewModel;
                    Debug.WriteLine("Enter key is caught");
                    logViewModel.FilterUpdateCmd.Execute(null);
                }
            }
            e.Handled = true;
        }
    }
}
